package com.ruoyi.project.myexperiment.controller;

import com.alibaba.fastjson.annotation.JSONType;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.myexperiment.domain.DetailsDto;
import com.ruoyi.project.myexperiment.domain.MyExment;
import com.ruoyi.project.myexperiment.domain.Result;
import com.ruoyi.project.myexperiment.service.MyExmentService;
import com.ruoyi.project.online_experimentStu.domain.OnlineExperimentStu;
import com.ruoyi.project.online_experimentStu.domain.Student;
import com.ruoyi.project.online_experimentStu.service.OnlineExperimentStuService;
import com.ruoyi.project.online_experimentStu.token.JwtUtil;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.patterns.IToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping("/website/myexment")
public class MyExmentController extends BaseController {

    private  String prefix="system/myexment";

    @Autowired
    private MyExmentService myExmentService;

    @Autowired
    private OnlineExperimentStuService onlineExperimentStuService;

    @RequiresPermissions("website:myexment:view")
    @GetMapping()
    public  String myexment(){
        return  prefix + "/myexment";
    }

    /**
     *查询我的实验
     */
    @RequiresPermissions("website:myexment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo selectExment(MyExment myExment)
    {
        startPage();
        myExment.setStudentId(getUserId());
        List<MyExment> list = myExmentService.selectExmentList(myExment);
        /*for (MyExment lists:list){
            if (lists.getClassAddress()!=null && lists.getOrderTime()!=null && lists.getSection()!=null){
                lists.setExperimentMessage(lists.getClassAddress().toString()+"-"+lists.getOrderTime().toString()+""+lists.getSection().toString());
            }
        }*/
        return getDataTable(list);
    }

    //进入实验详情页面
    @GetMapping("/details")
    public String addPage(String id,ModelMap mmap)
    {
        //判断此试验是否已经提交
        HashMap<String,Long> map=new HashMap<>();
        map.put("id", Long.valueOf(id));
        map.put("userId", getSysUser().getUserId());
        DetailsDto details1=myExmentService.seletExmentDetail2(map);
        DetailsDto details=myExmentService.seletExmentDetail(id);
        //獲取到查詢的資源id
        String accessoryIds=details.getAccessoryId();
        if(accessoryIds!=null){
            //根據查詢到的資源id,去獲取資源對應的網址
            String[] accessory= Convert.toStrArray(accessoryIds);
            List<String> path=myExmentService.getPathbyAccessoryId(accessory);
            if(path.size()==0){
                details.setAccessoryId(null);
            }else{
                //拼接對應地址路徑
                if(path.size()==1){
                    details.setAccessoryId(path.get(0)+",");
                }else{
                    String path2="";
                    for(String a:path){
                        path2+=a+",";
                    }
                    //將字符串加入到實體類
                    details.setAccessoryId(path2);
                }
            }
        }
        if(details1!=null){
            details.setExperimentShape(details1.getExperimentShape());
            mmap.put("details",details);
        }else{
            mmap.put("details",details);
        }
        return prefix + "/details";
    }

    /**
     * 进入实验详情页面
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/details2")
    public String addPage2(String id,ModelMap mmap)
    {
        HashMap<String,Long> map=new HashMap<>();
        String[] sArr=id.split(",");
        //根据实验id和学生id查找
        map.put("id",Long.valueOf(sArr[0]));
        map.put("userId",Long.valueOf(sArr[1]));
        DetailsDto details=myExmentService.seletExmentDetail2(map);
        mmap.put("details",details);
        return "experimentcheck/details";
    }


    /**
     * 获取在线实验u3d传来的结果
     * @param result
     * @param request
     * @return
     */
    @PostMapping("/getExperimentResult")
    @ResponseBody
    @CrossOrigin
    public boolean getExperimentResult(@RequestBody Result result,HttpServletRequest request){
        String str="";
        /**
         * 获取用户和实验id
         * 如果参数keys中索引0不是“token” 或者values索引0为" "即返回false
         */
        if(StringUtils.isEmpty(result.getValues()[0]) || result.getValues()[0]==null || !result.getKeys()[0].equals("token")){
            return false;
        }else{
            for(int i=1;i<result.getKeys().length;i++){
                str+=result.getKeys()[i]+":"+result.getValues()[i]+"/";
            }
            str=str.substring(0,str.length()-1);
        }
        Student student=JwtUtil.unsign(result.getValues()[0], Student.class);
        /**
         * 实验对象
         */
        if(student!=null){
            //执行插入操作
            OnlineExperimentStu onlineExperimentStu=new OnlineExperimentStu();
            onlineExperimentStu.setStudentId(student.getStudentId());
            onlineExperimentStu.setExperimentTeaId(student.getExperimentTeaId());
            onlineExperimentStu.setU3dScore(str);
            //执行更新操作  即添加在线实验结果
            boolean flag=onlineExperimentStuService.updateExperimentStu(onlineExperimentStu);
            if(flag==true){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 提交页面
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DetailsDto detailsDto,HttpServletRequest request)
    {
        //获取当前用户
        User user = getSysUser();
        //获取session
        HttpSession session=request.getSession();
        //session.setAttribute(user.getUserId()+user.getUserName(),"第一阶段：90分，第二阶段：100分");
        //获取存储数据
        String experimentResult=(String)session.getAttribute(user.getUserId()+user.getUserName());
        //将存储的实验数据给取出赋值
        detailsDto.setExperimentResult(experimentResult);
        //获取当前提交实验结果的用户id
        int id= Math.toIntExact(user.getUserId());
        detailsDto.setUserId(id);
        detailsDto.setUserName(user.getUserName());
        //System.err.println(detailsDto);
        /**
         * 根据实验id和用户id获取试验信息
         * 判断是否已经提交过
         */
        //System.out.println(detailsDto.getId());
        HashMap<String,Long> map=new HashMap<>();
        map.put("id", (long) detailsDto.getId());
        map.put("userId", (long) id);
        DetailsDto details1=myExmentService.seletExmentDetail2(map);
        //System.err.println("2"+details1);
       /*
         * 如果该实验提交的用户再次提交，则更新内容
         */
       /* for(DetailsDto a:details1){*/
        if(details1!=null) {
            if (details1.getUserId() == id) {
                return toAjax(myExmentService.updateDetail(detailsDto));
            } else {
                return toAjax(myExmentService.insertDetail(detailsDto));
            }
        }else{
            //System.err.println(detailsDto);
            return toAjax(myExmentService.insertDetail(detailsDto));
        }
       /* }
        return AjaxResult.success("修改完成");*/
    }

    @PostMapping("/add2")
    @ResponseBody
    public AjaxResult addSave2(DetailsDto detailsDto)
    {
        System.err.println(detailsDto);
        return toAjax(myExmentService.insertDetailtwo(detailsDto));
    }


    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, DetailsDto fileInfo) throws IOException
    {
        //System.out.println(file);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);

        //System.err.println("fileName"+fileName);
        /**获取当前用户*/
        User user=getSysUser();
        int userId= Math.toIntExact(user.getUserId());
        fileInfo.setUserId(userId);
        //System.err.println(fileInfo);
        //fileInfo.setId(id);
        fileInfo.setFilePath(fileName);

       /* *//**
         * 判断表中有没有数据
         *//*
        boolean flag=myExmentService.getById(fileInfo);
        if(flag){
            return toAjax(myExmentService.insertFileInfo(fileInfo));
        }else{
            return toAjax(myExmentService.insertDetailDao(fileInfo));
        }*/
        return toAjax(myExmentService.insertFileInfo(fileInfo));
    }


    /**
     * 学生附件下载
     * 因为教师会选择资源或者还会另外上传文件
     * 所以打成压缩包再下载
     * @param resource
     * @param response
     * @param request
     * @throws Exception
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource,HttpServletResponse response,HttpServletRequest request)
            throws Exception
    {
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        //System.out.println(localPath);
        //获取所有的文件地址(数据库中的)，包括资源和教师上传
        String[] resources=resource.substring(0,resource.length()-1).split(",");
        //System.err.println(Arrays.toString(resources));
        //存储所有文件的绝对路径
        List<File> resources1=new ArrayList<File>();
        //System.err.println(resource);
        for(String a:resources){
            // 绝对路径 即本地地址+数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(a, Constants.RESOURCE_PREFIX);
            resources1.add(new File(downloadPath));
        }
        //设置压缩文件
        String str= UUID.randomUUID()+".zip"; //随机获取压缩文件名
        File zipfile=new File(localPath+"/"+ str);
        byte[] buf=new byte[1024];
        try {
            //ZipOutputStream类：完成文件或文件夹的压缩
            ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipfile));
            for(int i=0;i<resources1.size();i++){
                FileInputStream in=new FileInputStream(resources1.get(i));
                out.putNextEntry(new ZipEntry(resources1.get(i).getName()));
                int len;
                while((len=in.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            //System.out.println("压缩完成.");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }// 数据库资源地址
        String downloadPath = localPath +"/"+ str;
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, str));
        File file=new File(downloadPath);
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] buff =  new byte[1024];
        int len2=0;
        while ((len2 = in.read(buff)) != -1) {
            out.write(buff, 0, len2);
        }
        in.close();
    }
}
